'''
Created on 21/08/2012

@author: Nrai
'''

import os
import sys
from src.ex import paletteexceptions
from validatepalette import validate_palette, get_ptype

PATH = "C://Documents and Settings//Nrai//Escritorio//"


def decode_palette(filename, output):
    
    '''
        Receives a palette file and output as parameters.
        Returns an object based on the output type (str or list)
    '''
    #placeholder for config
    fext = filename.split(".")[1]   #extract the extension from the name
    palette_properties = {"act" : {"length" : 768, "channels" : 3} }
    length = palette_properties[fext]["length"]
    channels = palette_properties[fext]["channels"]
    
    try:
        pfile = open(filename, "r")
    except IOError:
        raise paletteexceptions.PaletteFileError(filename)
    if validate_palette(pfile, fext):
        pfilename = os.path.join(PATH, filename)
        decoder = getattr (sys.modules[__name__], 
                           "file_to_{o}".format(o = output))
        return decoder(pfile, pfilename)

def file_to_str(pfile, channels, length):
    
    palette = pfile.read()
    return palette

def file_to_list(pfile, channels, length):
    
    palette = [[ord(channel) for channel in color] for color in (pfile.read(channels) for x in xrange(length / channels))]
    return palette